<template>
  <view class="Index">
    <swiper
      class="screen-swiper square-dot"
      :indicator-dots="true"
      :circular="true"
    >
      <swiper-item
        v-for="(item, index) in schoolImgs"
        :key="index"
        @tap="previewSchoolImg(schoolImgs, index)"
      >
        <image :src="isShow ? item.url : ''" mode="aspectFill"></image>
      </swiper-item>
    </swiper>

    <view class="margin-sm"></view>

    <view
      class="flex justify-between padding bg-white school-top-wrap solids-bottom"
    >
      <view class="flex-sub margin-xs">
        <image
          :src="isShow ? schoolImgs[0]?.url : ''"
          class="school-img"
          @tap="previewSchoolImg(schoolImgs[0].url)"
        ></image>
      </view>

      <view class="flex-twice margin-xs" style="white-space: nowrap">
        <text class="text-black text-bold text-lg">汕头开放大学老年大学</text>
      </view>

      <view>
        <button open-type="share" class="cu-btn no-border bg-white fr">
          <text class="cuIcon-share text-yellow"></text>
        </button>
      </view>
    </view>
    <!-- 
    <view class="flex align-center justify-between bg-white padding">
      <view class="flex align-center">
        <text class="cuIcon-locationfill"></text>
        <text class="text-gray text-sm margin-left-xs">汕头市金平区乐山路8号</text>
      </view>
      <view class="cuIcon-phone text-blue solids-left padding-left" @tap="contactSchool"></view>
    </view>
 -->
    <scroll-view scroll-x class="bg-white nav">
      <view class="flex text-center">
        <view
          class="cu-item flex-sub"
          :class="index === curTabIdx ? 'text-blue cur' : ''"
          v-for="(item, index) in tabs"
          :key="index"
          @tap="tabSelect"
          :data-id="index"
        >
          {{ item }}
        </view>
      </view>
    </scroll-view>

    <view v-if="curTabIdx === 0">
      <view class="margin-top">
        <!--  <view class="cu-bar bg-white solid-bottom">
          <view class="action">
            <text class="cuIcon-titles text-blue"></text>
            <text class="text-xl text-bold">学校负责人</text>
          </view>
        </view> -->

        <!-- <view class="cu-bar bg-white">
          <view class="action">
            <text class="text-lg text-black">xxx</text>
          </view>
        </view> -->
      </view>

      <view class="margin-top">
        <view class="cu-bar bg-white solid-bottom">
          <view class="action">
            <text class="cuIcon-titles text-blue"></text>
            <text class="text-xl text-bold">学校介绍</text>
          </view>
        </view>

        <view class="cu-bar bg-white">
          <view class="action margin-top">
            <!-- <rich-text class="text-black" style="text-indent: 2em;" :nodes="schoolDesc" /> -->
            <text space="nbsp">{{ isShow ? schoolDesc : "" }}</text>
          </view>
        </view>
      </view>

      <view class="margin-top">
        <view class="cu-bar bg-white solid-bottom">
          <view class="action">
            <text class="cuIcon-titles text-blue"></text>
            <text class="text-xl text-bold">学校图片</text>
          </view>
        </view>

        <view class="bg-white">
          <swiper
            class="card-swiper"
            :indicator-dots="false"
            :circular="false"
            :autoplay="true"
            interval="3000"
            duration="500"
          >
            <swiper-item
              v-for="(item, index) in schoolImgs"
              :key="index"
              @tap="previewSchoolImg(schoolImgs, index)"
            >
              <view class="swiper-item">
                <image :src="isShow ? item.url : ''" mode="aspectFill"></image>
              </view>
            </swiper-item>
          </swiper>
        </view>
      </view>
    </view>

    <view v-if="curTabIdx === 2">
      <view class="margin-top">
        <view class="cu-bar bg-white solid-bottom">
          <view class="action">
            <text class="cuIcon-titles text-blue"></text>
            <text class="text-xl text-bold">公告信息</text>
          </view>
        </view>

        <view class="cu-list menu">
          <!-- <view class="formdata">
		  	<view class="formdata-item">
		  		<view class="text">
		  			<text>标题名称</text>
		  		</view>
		  		<view class="input">
		  			<input placeholder="请输入标题名称" @input="OnXXBT" />
		  		</view>
		  	</view>
		  </view> -->
          <view
            class="cu-item"
            v-for="item in DATA"
            :key="DATA.XX_ID"
            @tap="showInformation(item.XX_ID)"
          >
            <view class="content flex">
              <text class="cuIcon-tagfill text-grey" style="color: red"></text>
              <text class="text-grey test-ellipsis">{{ item.XX_BT }}</text>
            </view>
          </view>
          <view v-if="!DATA.length" class="text-sm text-center"
            >-- 暂无数据 --</view
          >
          <view class="cu-form-group" v-if="COUNTNUM > 1">
            <view class="title" @tap="firstPage()"
              ><text class="check-info-btn">首页</text></view
            >
            <view class="title" @tap="lastPage()"
              ><text class="check-info-btn">上一页</text></view
            >
            <view class="title">{{ PageAn }}/{{ COUNTNUM }}</view>
            <view class="title" @tap="nextPage()"
              ><text class="check-info-btn">下一页</text></view
            >
            <view class="title" @tap="endPage()"
              ><text class="check-info-btn">尾页</text></view
            >
          </view>
        </view>
      </view>
    </view>

    <view v-if="curTabIdx === 1">
      <view class="margin-top">
        <view class="cu-bar bg-white solid-bottom margin-bottom-sm">
          <view class="action">
            <text class="cuIcon-titles text-blue"></text>
            <text class="text-xl text-bold">专业班级</text>
          </view>
        </view>

        <view class="cu-form-group">
          <view class="title">专业</view>
          <picker
            @change="onPickMajor"
            :value="curPickMajorIdx"
            :range="majorOpts"
            range-key="label"
          >
            <view class="picker">
              {{
                curPickMajorIdx > -1
                  ? majorOpts[curPickMajorIdx]["label"]
                  : "请选择"
              }}
            </view>
          </picker>
        </view>

        <view v-if="newclassList.length > 0" style="margin-bottom: 80rpx">
          <view
            class="cu-card"
            :id="`card-${item.CLASS_ID}`"
            v-for="item in newclassList"
            :key="item.CLASS_ID"
          >
            <view
              class="cu-item shadow padding card-item"
              style="margin-top: 20rpx; margin-bottom: 10rpx"
            >
              <view class="cu-tag bg-green sm" v-if="item.SH_FLAG == '1'"
                >需审核</view
              >
              <view class="cu-list menu">
                <view class="cu-item">
                  <view class="content flex-sub">
                    <view class="text-black text-bold">{{
                      item.CLASSNAME
                    }}</view>

                    <view class="text-gray text-sm flex">
                      <text>课任老师姓名： {{ item.TEACHERNAME }}</text>
                    </view>

                    <view class="text-gray text-sm flex">
                      <text>专业： {{ item.MAJOR_NAME }}</text>
                    </view>
                    <view class="text-gray text-sm flex">
                      <text>开课时间： {{ item.S_KK_DATE }}</text>
                    </view>

                    <view class="text-gray text-sm flex">
                      <text>上课时间： {{ item.SKSJSNR }}</text>
                    </view>

                    <view class="text-gray text-sm flex margin-tb-xs">
                      <view
                        class="cu-tag radius bg-red light"
                        style="position: relative; margin-left: 0"
                        >{{ item.DSZ_FLAGNR }}</view
                      >
                    </view>
                  </view>
                </view>

                <view class="cu-item">
                  <view class="flex flex-direction text-red text-df">
                    <view class="text-price"
                      >{{ getPrice(+item.SFJE1, false)
                      }}<text class="text-sm margin-left-xs text-gray"
                        >低于50周岁</text
                      ></view
                    >
                    <view class="text-price"
                      >{{ getPrice(+item.SFJE2, false)
                      }}<text class="text-sm margin-left-xs text-gray"
                        >50周岁（含）以上</text
                      ></view
                    >
                  </view>
                  <!--                  <template v-if="ROLE_ID === 4">-->
                  <!--                    <button v-if="!isSelectOther" class="cu-btn bg-blue round shadow" @tap="toEnroll(item.CLASS_ID)">立即报名</button>-->
                  <!--                    <checkbox-group @change="onCheckChange" v-else :data-id="item.CLASS_ID">-->
                  <!--                      <checkbox class="round blue" :value="item.CLASS_ID" :checked="selectedIds.includes(item.CLASS_ID)"></checkbox>-->
                  <!--                    </checkbox-group>-->
                  <!--                  </template>-->
                </view>
              </view>
            </view>
          </view>
          <load-more :status="loadStatus" />
        </view>

        <view v-else class="text-gray text-center margin-top text-sm"
          >-- 暂无数据 --</view
        >
      </view>
    </view>
  </view>

  <view class="flex justify-center" v-if="isSelectOther">
    <button
      class="cu-btn round block bg-blue float-btn shadow"
      @tap="confirmEnroll"
    >
      确认报名
    </button>
  </view>
</template>

<script setup lang="ts">
import { usePreview } from "../../utils/usePreview";
import { useSchoolInfo } from "./useSchoolInfo";
import { computed, reactive, ref, watch, watchEffect } from "vue";
import { useClassesNew } from "./useClasses";
import { usePagination } from "../../utils/usePagination";
import LoadMore from "../../components/loadmore/index.vue";
import { onPullDownRefresh } from "@dcloudio/uni-app";
import { useLogin } from "../account/useLogin";
import { usePrice } from "../../utils/usePrice";
import { useStore } from "vuex";
import { onShow, onLoad } from "@dcloudio/uni-app";
import { useAnnouncementTitleList } from "./useAnnoun";

import { getMajorOpt } from "../../api/options";

const { initAnnouncementTitleList, DATA, COUNTNUM }: any =
  useAnnouncementTitleList();
const { state, dispatch, commit } = useStore();
const { getPrice } = usePrice();
const { previewImage } = usePreview();
const {
  schoolImg,
  banners,
  schoolDesc,
  schoolImgs,
  contactSchool,
  previewSchoolImg,
  inintgetSchoolInfo,
}: any = useSchoolInfo();
const curTabIdx = ref(0);
const tabs = ["学校信息", "专业班级", "公告信息"];
const { classList, initClassList, total } = useClassesNew();

const curPickMajorIdx = ref(0);
const majorOpts = ref<any>([]);
function onPickMajor(e: any) {
  curPickMajorIdx.value = e.detail.value;
}
const newclassList = computed(() => {
  return classList.value.filter((v) => {
    return v.MAJOR_ID == majorOpts.value[curPickMajorIdx.value]?.value;
  });
});

const selectedIds = reactive<number[]>([]);
const isSelectOther = ref(false);
const { hasLogIn, isFilledData, ROLE_ID, hasEnroll } = useLogin();
const pageSize = 20;
const { page, loadStatus } = usePagination({
  page: 1,
  pageSize,
  onPageChange: initClassList,
  args: computed(() => selectedIds.join(";")),
  startReachBottom: computed(() => curTabIdx.value === 1),
});
const PageAn = ref<any>("1");
const XX_BT = ref<any>("");
const isShow = ref(true);
onLoad(async (options) => {
  if (options.reload) {
    await dispatch("logout");
    return false;
  }
  inintgetSchoolInfo().then((res) => {
    if (res.length == 0) {
      isShow.value = false;
    }
  });
  initAnnouncementTitleList();

  //专业班级
  getMajorOpt(state.user.userInfo.CUSER_ID || "0") //拼接专业列表
    .then((res) => {
      if (res.ERROR[0].errcode == "0") {
        majorOpts.value.push(
          ...res.DAT.map((item) => ({
            value: String(item.MAJOR_ID),
            label: item.MAJOR_NAME,
          }))
        );
      } else {
        uni.showToast({
          title: res.ERROR[0].error,
          icon: "none",
          mask: true,
        });
      }
    })
    .catch((err) => {
      uni.showToast({
        title: "获取专业列表失败",
        icon: "none",
        mask: true,
      });
    });
});
onShow(() => {
  if (state.user.isUpdataSchoolinfo) {
    //使用全局状态管理判断首页是否被修改
    inintgetSchoolInfo().then((res) => {
      if (res.length == 0) {
        //没有返回数据
        isShow.value = false; //不显示页面图片资源
      } else {
        isShow.value = true; //显示页面图片资源
      }
    });
    commit("SET_SCHOOLINFO", false); //使用全局状态管理重新赋值为初始值
  }
});
watch(
  () => curTabIdx.value,
  (value) => {
    if (value === 1) {
      refreshClassList();
    }

    if (value === 0) {
      selectedIds.length = 0;
      isSelectOther.value = false;
    }
  }
);

function OnXXBT(e: any) {
  XX_BT.value = e.detail.value;
  PageAn.value = "1";
  initAnnouncementTitleList({
    XX_BT: XX_BT.value,
    Page: "1",
    PageSize: "10",
  });
}
function firstPage() {
  PageAn.value = "1";
  initAnnouncementTitleList({
    XX_BT: XX_BT.value,
    Page: PageAn.value,
    PageSize: "10",
  });
}

function lastPage() {
  if (PageAn.value > 1) {
    PageAn.value--;
    initAnnouncementTitleList({
      XX_BT: XX_BT.value,
      Page: PageAn.value,
      PageSize: "10",
    });
  }
}

function nextPage() {
  if (PageAn.value < COUNTNUM.value) {
    PageAn.value++;
    initAnnouncementTitleList({
      XX_BT: XX_BT.value,
      Page: PageAn.value,
      PageSize: "10",
    });
  }
}

function endPage() {
  PageAn.value = COUNTNUM.value;
  initAnnouncementTitleList({
    XX_BT: XX_BT.value,
    Page: COUNTNUM.value,
    PageSize: "10",
  });
}

watchEffect(() => {
  loadStatus.value = total.value <= pageSize ? "over" : "loadmore";
});

onPullDownRefresh(() => {
  if (curTabIdx.value === 1) {
    refreshClassList();
  }
  inintgetSchoolInfo();
  initAnnouncementTitleList();
  uni.stopPullDownRefresh();
});

function onCheckChange(e: any) {
  const id = e.currentTarget.dataset.id;

  refreshClassList();
  if (e.detail.value[0]) {
    selectedIds.push(id);

    setTimeout(() => {
      uni.pageScrollTo({
        selector: `#card-${id}`,
        duration: 0,
        success: () => {},
        fail: () => {},
      });
    }, 300);
  } else {
    selectedIds.splice(selectedIds.indexOf(id), 1);

    setTimeout(() => {
      uni.pageScrollTo({
        selector: `#card-${selectedIds[selectedIds.length - 1]}`,
        duration: 0,
        success: () => {},
        fail: () => {},
      });
    }, 300);
  }
}

function refreshClassList() {
  classList.value.length = 0;
  // 为了触发响应式更新
  page.value = -100;
  page.value = 1;
  loadStatus.value = "loadmore";
}

function clearSelect() {
  selectedIds.length = 0;
  isSelectOther.value = false;
}

function confirmEnroll() {
  uni.navigateTo({
    url: `/pages/enroll/index?classes=${encodeURIComponent(
      JSON.stringify(
        selectedIds.map((id) =>
          classList.value.find((item) => item.CLASS_ID === id)
        )
      )
    )}`,
    success: () => {
      clearSelect();
    },
  });
}

function toEnroll(classId: number) {
  if (!hasLogIn.value) {
    uni.showModal({
      title: "提示",
      content: "尚未登录，是否前往登录",
      success: ({ confirm }) => {
        if (confirm) {
          uni.switchTab({
            url: "/pages/account/index",
          });
        }
      },
    });

    return;
  }

  if (!isFilledData.value) {
    uni.showModal({
      title: "提示",
      content: "尚未完善资料，是否填写",
      success: ({ confirm }) => {
        if (confirm) {
          uni.navigateTo({
            url: "/pages/profile/student",
            success: () => {
              clearSelect();
            },
          });
        }
      },
    });
    return;
  }

  if (hasEnroll.value) {
    uni.showModal({
      title: "提示",
      content: "已存在报名记录，是否前往修改？",
      success: ({ confirm }) => {
        if (confirm) {
          uni.navigateTo({
            url: "/pages/enroll/list",
            success: () => {
              clearSelect();
            },
          });
        }
      },
    });
    return;
  }

  uni.showModal({
    title: "提示",
    content: "是否继续选择参加其他专业班？",
    cancelText: "不选其他",
    confirmText: "继续选择",
    success: ({ confirm, cancel }) => {
      selectedIds.push(classId);
      if (confirm) {
        refreshClassList();
        isSelectOther.value = true;
        uni.pageScrollTo({
          selector: `#card-${classId}`,
          duration: 0,
          success: () => {},
          fail: () => {},
        });
        return;
      }

      if (cancel) {
        uni.navigateTo({
          url: `/pages/enroll/index?classes=${encodeURIComponent(
            JSON.stringify(
              selectedIds.map((id) =>
                classList.value.find((item) => item.CLASS_ID === id)
              )
            )
          )}`,
          success: () => {
            clearSelect();
          },
        });
        return;
      }
    },
  });
}

function showInformation(XX_ID: string) {
  uni.navigateTo({
    url: `/pages/index/bulletinDetails?XX_ID=${XX_ID}`,
  });
}

function tabSelect(e: any) {
  curTabIdx.value = e.currentTarget.dataset.id;
}
</script>

<style lang="scss">
.Index {
  .school-top-wrap {
    height: 200rpx;

    .school-img {
      border-radius: 8rpx;
      width: 100%;
      height: 100%;
    }
  }

  .card-item {
    position: relative;
    .cu-tag {
      position: absolute;
      right: 0;
      z-index: 2;
    }
  }
}
.test-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}
.formdata {
  background-color: white;
  .formdata-item {
    padding: 0 32rpx 0 32rpx;
    border-bottom: 4rpx #f7f8fc solid;
    width: 100%;
    height: 110rpx;
    display: flex;
    align-items: center;

    .text {
      margin-right: 32rpx;
    }
  }
}
</style>
